package com.xzy.sms.web.domain.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xzy.sms.core.utils.TemplateUtils;
import com.xzy.sms.entity.SendSmsRequest;
import com.xzy.sms.exception.SendSmsException;
import com.xzy.sms.service.SendSmsService;
import com.xzy.sms.utils.SmsUtils;
import com.xzy.sms.web.rest.RestObject;

/**
 * 以REST方式提供给第其它应用调用短信发送的接口
 * @author huchangjiang
 * @since 1.0
 * @version 2016年1月11日 huchangjiang
 */
@Controller
@RequestMapping("/api")
public class ApiController {
    
    /** 日志打印器 */
    protected static Logger logger = LoggerFactory.getLogger(ApiController.class);
    
    /** FIXME */
    @Autowired
    private SendSmsService sendSmsService;
    
    /**
     * api发送接口调用
     * @param ssr
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public RestObject send(SendSmsRequest ssr, HttpServletRequest request) {
        RestObject result = validRequest(ssr);
        if (result != null) {
            return result;
        }
        ssr.setRawSign(builderRawSign(request));
        try {
            ssr.setParameters(TemplateUtils.getTemplateParameter(request));
            sendSmsService.sendSms(ssr);
        } catch (SendSmsException ex) {
            logger.error("短信发送失败，message:{},sms:{}", ex.getMessage(), ssr);
            return RestObject.newError(ex.getMessage());
        } catch (Exception ex) {
            logger.error("短信发送失败", ex);
            return RestObject.newError("短信发送失败");
        }
        
        return RestObject.newOk("success");
    }
    
    /**
     * 校验请求数据
     * @param ssr
     * @return
     */
    private RestObject validRequest(SendSmsRequest ssr) {
        // TODO 自动生成方法存根注释，方法实现时请删除此注释
        return null;
    }
    
    /**
	 * 获取request参数拼接为待签名字符串
	 */
	public String builderRawSign(HttpServletRequest request) {
		Map<String, String> paramMap = new HashMap<String, String>();
		Enumeration<String> paramNames = request.getParameterNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			paramValue = request.getParameter(paramName);
			if(StringUtils.isNotEmpty(paramValue)){
				paramMap.put(paramName, paramValue);
			}
		}
		return SmsUtils.buildRawSign(paramMap);
	}
}
